<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage,ElMessageBox, type UploadProps} from 'element-plus'
import type { EmpModelArray, EmpModel, SearchEmpModel, PaginationParam,DeptModelArray,EmpExprModel } from '@/api/model/model'
import { queryPageApi,addApi,deleteApi, queryInfoApi,updateApi } from '@/api/emp';
import{queryAllApi}from '@/api/dept'



//声明列表展示数据
let tableData = ref<EmpModelArray>([])

onMounted(() => {
  queryEmp()
  queryDept()
 })

const searchEmp = ref<SearchEmpModel>({
  name: '',
  gender: '',
  begin: '',
  end: '',
  date: []
})

const fenyeParam = ref<PaginationParam>({
  currentPage: 1,
  pageSize: 5,
  total: 0
})
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

/* 页面变化 */
const handleSizeChange = (val: number) => {
  fenyeParam.value.pageSize = val
  console.log(`${val} items per page`)
  queryEmp()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  fenyeParam.value.currentPage = val
  queryEmp()
}

//条件查询
const queryEmp = async () => {
  console.log(searchEmp.value)
  if (searchEmp.value.date.length > 0) {
    searchEmp.value.begin = searchEmp.value.date[0]
    searchEmp.value.end = searchEmp.value.date[1]
  } else {
    //没有选择时间范围
    searchEmp.value.begin = ''
    searchEmp.value.end = ''
  }

  const res = await queryPageApi(
    searchEmp.value.begin,
    searchEmp.value.end,
    searchEmp.value.gender,
    searchEmp.value.name,
    fenyeParam.value.currentPage,
    fenyeParam.value.pageSize)

  if (res.code) {
    tableData.value = res.data.rows,
      fenyeParam.value.total = res.data.total
  }

}

//表单清空
const resetQueryEmp = () => {
  searchEmp.value.name = ''
  searchEmp.value.gender = ''
  searchEmp.value.begin = ''
  searchEmp.value.end = ''
  searchEmp.value.date = []
  fenyeParam.value.currentPage = 1
  queryEmp()
}

//隐藏新增员工对话框
const dialogFormVisible = ref(false)
//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 },{ name: '讲师', value: 2 },{ name: '学工主管', value: 3 },{ name: '教研主管', value: 4 },{ name: '咨询师', value: 5 },{ name: '其他', value: 6 }])
//部门列表数据
const deptName=ref<DeptModelArray>([])
const queryDept=async()=>{
  const res=await queryAllApi()
  if(res.code){
    deptName.value=res.data
  }  
}
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
//设置对话框表单宽度
const labelWidth = '80px'
//定义一个员工对象给对话框使用
const emp = ref<EmpModel>({
  username: '',
  password: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  image: '',
  entryDate: '',
  deptId: '',
  exprList: []
})

//清空对话框表单数据
const clear=()=>{
  emp.value={
    username: '',
    password: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    image: '',
    entryDate: '',
    deptId: '',
    exprList: []
  }
}


//打开对话框
const add = () => {
  emphh.value='新增员工'
  dialogFormVisible.value = true
 }
 //取消操作清空对话框
 const quxiao=()=>{
  dialogFormVisible.value = false
  clear()
 }

const emphh=ref<string>('')

//添加或者修改员工
const addEmpby=async()=>{
  let res=null
if(emp.value.exprList){
  emp.value.exprList.forEach(expr=>{
    expr.begin=expr.exprDate[0]
    expr.end=expr.exprDate[1]
  })
}
if(emp.value.id){
  res=await updateApi(emp.value)
}else{
  res=await addApi(emp.value)
}
   if(res.code){  
    ElMessage.success('操作成功')
  } else{
    ElMessage.error('操作失败')
  }
  clear()
 dialogFormVisible.value=false
 queryEmp()
}

// 图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
   emp.value.image = response.data; 
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片格式不支持!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过 10 MB!')
    return false
  }
  return true
}

//动态添加工作经历 .
const addWorkItem = () => {
  emp.value.exprList.push({exprDate: [],begin: '',end: '',company: '',job: ''})
}
//动态删除工作经历 .
const delWorkItem = (expr: EmpExprModel) => {
  if(emp.value.exprList) {
    const index = emp.value.exprList.indexOf(expr)
    if(index != -1){
      emp.value.exprList.splice(index,1)
    }
  }
}


// 批量删除  start
//选中对象的容器
const multipleSelection = ref<EmpModel[]>([])

//选中对象的id容器
const selectionIds = ref<(number | undefined)[]>([])


//如果多选框选择了，就会回调次方法 其中val就是最新的值
const handleSelectionChange = (val: EmpModel[]) => {
  multipleSelection.value = val

  if (val.length == 0) {
    selectionIds.value = []
  } 

  console.log("批量删除，对象容器：", multipleSelection)
  //观察控制台，发i发现输出的是一个一个的员工对象
  //思考：批量删除的接口，需要传递的ids=1，2，3
  //解决方案：对象，对象2，对象3===》id1，id2，id3

  multipleSelection.value.map((item) => {
    //获取到每个对象item 将其中的id，添加到selectionIds数组中
    selectionIds.value.push(item.id)
  })

  // 发现每次变化，都会添加，导致selectionIds会出现重复id

  selectionIds.value = Array.from(new Set(selectionIds.value))

  // 此时发现id已经去重了，格式：[2,3,4,5,6]可以向后台提交了,

}

//批量删除
const deleteByIds = async () => {

//判断ids是否为空

if (selectionIds.value.length == 0) {

  ElMessage.error('请勾选要删除的数据！！')
  return
}

ElMessageBox.confirm(
  '您确认删除此数据吗？',
  '删除员工',
  {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }
)
  .then(async () => {//点击确认按钮

    //发起删除请求，根据结果，显示Message

    //由于批量删除的数组，格式：[1,3,4,5],传给后台的数据是这样的1,3,4

    let ids = selectionIds.value.join(',')//1,3,4

    const res = await deleteApi(ids)
    // res 结果{code：1，message：‘’，data：null }
    if (res.code) {//判断code是否为0 如果并不是0，就是ture
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
    } else {

      ElMessage.error('删除失败')

    }

    selectionIds.value = [];//无论删除成功和失败，都将ids 清空

    //无论成功和失败，都需要重新发起列表请求，筛选页面
    queryEmp()



  })
  .catch(() => {//点击取消按钮
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}
//员工数据回显
const update=async(id:number)=>{
    clear()
    emphh.value='修改员工'
    dialogFormVisible.value=true
    const res=await queryInfoApi(id)
    if(res.code){
      emp.value=res.data
      if(emp.value.exprList){
        emp.value.exprList.forEach(expr=>{
          expr.exprDate=[expr.begin,expr.end]
        })
      }
    } 
}



const deleteByOneId=async(id:number)=>{
  ElMessageBox.confirm(
    '您确定删除这个员工吗？',
    '删除员工',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await deleteApi(id+'')
      if(res.code){
        ElMessage({
        type: 'success',
        message: '删除成功',
      })
      }else{
        ElMessage({
        type: 'error',
        message: '删除失败',
      })
      }
     queryEmp()
    })
    .catch(() => {//点击取消按钮
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
      })
}

</script>

<template>
  <h1>员工管理</h1>
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入姓名" />
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="请选择">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>

    <el-form-item label="入职时间">
      <el-date-picker v-model="searchEmp.date" type="daterange" range-separator="到" start-placeholder="开始时间"
        end-placeholder="结束时间" value-format="YYYY-MM-DD" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="queryEmp">查询</el-button>
      <el-button @click="resetQueryEmp">清空</el-button>
    </el-form-item>
  </el-form>

  <!-- 功能按钮 -->
  <el-button type="success" @click="add">+ 新增员工</el-button>
  <el-button type="danger" @click="deleteByIds">- 批量删除</el-button>
  <br><br>
  <br>

  <!-- 员工数据表格 -->
  <el-table :data="tableData" border style="width: 100%"  @selection-change="handleSelectionChange" fit>
    <!--  <el-table-column type="index" label="序号"  width="50"  align="center"/> -->
    <el-table-column type="selection" width="55px" />
    <el-table-column prop="name" label="姓名" width="130px" align="center" />
    <el-table-column prop="gender" label="性别" width="100px" align="center">
      <template #default="scope">
        <span v-if="scope.row.gender == 1">男</span>
        <span v-else-if="scope.row.gender == 2">女</span>
      </template>
    </el-table-column>
    <el-table-column prop="image" label="头像" align="center" >
      <template #default="scope">
        <el-image :src="scope.row.image"/>
      </template>
    </el-table-column>
    <el-table-column prop="deptName" label="所属部门" align="center" />
    <el-table-column prop="job" label="职位" width="100px" align="center">
      <template #default="scope">
        <span v-if="scope.row.job == 1">班主任</span>
        <span v-else-if="scope.row.job == 2">讲师</span>
        <span v-else-if="scope.row.job == 3">学工主管</span>
        <span v-else-if="scope.row.job == 4">教研主管</span>
        <span v-else-if="scope.row.job == 5">咨询师</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column prop="entryDate" label="入职时间" align="center" width="130px" />
    <el-table-column prop="updateTime" label="最后修改时间" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="update(scope.row.id)" >修改</el-button>
        <el-button size="small" type="danger" @click="deleteByOneId(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br><br>

  <!-- 数据分页 -->
  <div class="demo-pagination-block">
    <!-- <div class="demonstration">All combined</div> -->
    <el-pagination v-model:current-page="fenyeParam.currentPage" v-model:page-size="fenyeParam.pageSize"
      :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
      layout="total, sizes, prev, pager, next, jumper" :total="fenyeParam.total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>


  <!-- 新增员工 / 修改员工的 DiaLog对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="emphh">
    <el-form :model="emp">
      <!-- 第一行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" :label-width="labelWidth">
            <el-input v-model="emp.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" :label-width="labelWidth">
            <el-input v-model="emp.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" :label-width="labelWidth">
            <el-select v-model="emp.gender" placeholder="请选择" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" :label-width="labelWidth">
            <el-input v-model="emp.phone" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="薪资" :label-width="labelWidth">
            <el-input v-model="emp.salary" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" :label-width="labelWidth">
            <el-date-picker v-model="emp.entryDate" type="date" placeholder="请选择入职日期" value-format="YYYY-MM-DD"
              style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属部门" :label-width="labelWidth">
            <el-select v-model="emp.deptId" placeholder="请选择" style="width: 100%;">
              <!--  <el-option label="教研部" value="1" /> -->
              <!--  给活的部门名字数据 -->
              <el-option v-for="dept in deptName" :label="dept.name" :value="dept.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" :label-width="labelWidth">
            <el-select v-model="emp.job" placeholder="请选择" style="width: 100%;">
              <el-option v-for="job in jobs" :label="job.name" :value="job.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像" :label-width="labelWidth">
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="emp.image" :src="emp.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第六行 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="工作经历" :label-width="labelWidth">
            <el-button type="success" size="small" @click="addWorkItem">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 -->
      <el-row :gutter="5"  v-for="expr in emp.exprList">
        <el-col :span="10" >
          <el-form-item label="时间" size="small" :label-width="labelWidth" >
            <el-date-picker  v-model="expr.exprDate"   type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>

        <el-col :span="6" >
          <el-form-item label="公司" size="small" >
            <el-input   v-model="expr.company"   placeholder="公司名称" />
          </el-form-item>
        </el-col>

        <el-col :span="6" >
          <el-form-item label="职位" size="small" >
            <el-input  v-model="expr.job"    placeholder="职位名称" />
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small">
            <el-button type="danger" @click="delWorkItem(expr)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quxiao">取消</el-button>
        <el-button type="primary" @click="addEmpby">确定</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped>
.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
/* 表单性别框长度 */
.demo-form-inline .el-select {
  --el-select-width: 100px;
}

.avatar-uploader .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    text-align: center;
    border: 1px dashed #ccc;
    border-radius: 5px;
  }

</style>